from web.ais.TengXunYuanBao import JiChuBan
# import JiChuBan
import requests
import hashlib
import hmac

class FileOperate(JiChuBan.YuanBaoJiChuBan):
    def __init__(self):
        super().__init__()

    
    def sha1_to_string(self, x):
        """
        接收输入 x，将其进行 SHA-1 哈希处理并转换为十六进制字符串
        :param x: 输入数据，可以是字符串或字节类型
        :return: SHA-1 哈希处理后的十六进制字符串
        """
        if isinstance(x, str):
            # 如果 x 是字符串，将其编码为字节类型
            x = x.encode('utf-8')
        elif not isinstance(x, bytes):
            # 如果 x 既不是字符串也不是字节类型，尝试将其转换为字符串再编码
            x = str(x).encode('utf-8')
        # 创建 SHA-1 哈希对象
        sha1 = hashlib.sha1()
        # 更新哈希对象的数据
        sha1.update(x)
        # 获取十六进制字符串表示的哈希结果
        return sha1.hexdigest()
    def hmac_sha1_to_string(self, o,y):
        """
        接收密钥 y 和消息 o，进行 HMAC-SHA1 计算并转换为十六进制字符串
        :param y: 密钥，字节类型或可编码为字节类型的数据
        :param o: 消息，字节类型或可编码为字节类型的数据
        :return: HMAC-SHA1 计算后的十六进制字符串
        """
        if isinstance(y, str):
            y = y.encode('utf-8')
        if isinstance(o, str):
            o = o.encode('utf-8')
        # 创建 HMAC 对象，使用 SHA1 算法
        h = hmac.new(y, o, hashlib.sha1)
        # 获取十六进制字符串表示的结果
        return h.hexdigest()

    # 获取文件的size
    def obj2str(self,file_size, file_path, response):
        Host = response['bucketName'] + "." + response['accelerateDomain']
        return f"content-length={file_size}&host={Host}"

    # 上传文件到腾讯元宝
    def upload_file(self, file_path, file_size):
        json_data = {
            'fileName': file_path,
            'docFrom': 'localDoc',
            'docOpenId': '',
        }
        # 获取上传信息
        UserInfo = requests.post(f'{self.domain}/api/resource/genUploadInfo', cookies=self.cookies, headers=self.headers, json=json_data).json()
        UserInfo['code'] = 200
        UserInfo['size'] = file_size
        # S, b
        b = self.hmac_sha1_to_string(f"{UserInfo['startTime']};{UserInfo['expiredTime']}", UserInfo['encryptTmpSecretKey'])
        s = "\n".join(["sha1", f"{UserInfo['startTime']};{UserInfo['expiredTime']}",self.sha1_to_string( "\n".join( ['put', UserInfo['location'], '',self.obj2str(file_size, file_path, UserInfo) , ""])) , ""])
        signature = self.hmac_sha1_to_string(s,b)
        headers = {
            'Accept': '*/*',
            'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
            'Authorization': f'q-sign-algorithm=sha1&q-ak={UserInfo['encryptTmpSecretId']}&q-sign-time={UserInfo['startTime']};{UserInfo['expiredTime']}&q-key-time={UserInfo['startTime']};{UserInfo['expiredTime']}&q-header-list=content-length;host&q-url-param-list=&q-signature={signature}',
            'Cache-Control': '',
            'Connection': 'keep-alive',
            'Content-Length': str(file_size),
            'Content-Type': 'application/octet-stream',
            'Origin': 'https://yuanbao.tencent.com',
            'Referer': 'https://yuanbao.tencent.com/',
            'Sec-Fetch-Dest': 'empty',
            'Sec-Fetch-Mode': 'cors',
            'Sec-Fetch-Site': 'cross-site',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36 Edg/135.0.0.0',
            'sec-ch-ua': '"Microsoft Edge";v="135", "Not-A.Brand";v="8", "Chromium";v="135"',
            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': '"Windows"',
            'x-cos-security-token': UserInfo['encryptToken'],
        }
        # 请求url
        url = f"https://{UserInfo['bucketName']}.{UserInfo['accelerateDomain']}{UserInfo['location']}"
        response = requests.put(url, headers=headers, data=open(file_path, 'rb').read())
        if response.status_code == 200:
            return UserInfo
        else:
            UserInfo['code'] = response.status_code
            return UserInfo

    

if __name__ == "__main__":
    file_path = 'test.html'  # 替换为实际文件路径
    files = FileOperate()
    print(files.upload_file(file_path))
